<?php
namespace doumiaoduo\aliyun\actions;

use OSS\Core\OssException;
use OSS\OssClient;
use yii\base\Action;

class WatermarklistAction extends Action{
    private $_config;

    private $endpoint;
    private $accessKeyId;
    private $accessKeySecret;
    private $bucket;
    private $ossImageProcessUrl;
    private $ossClient;
    private $filepath_prefix;
    public function init(){
        $this->_config = \Yii::$app->params['aliyun_oss'];
        $this->endpoint = $this->_config['OSS_ENDPOINT'];
        $this->accessKeyId = $this->_config['OSS_ACCESS_ID'];
        $this->accessKeySecret = $this->_config['OSS_ACCESS_KEY'];
        $this->bucket = $this->_config['OSS_TEST_BUCKET'];
        $this->ossImageProcessUrl = $this->_config['OSS_IMG_PROCESS'];
        $this->ossClient = new OssClient($this->accessKeyId,$this->accessKeySecret,$this->endpoint);
        $this->filepath_prefix = \Yii::$app->params['aliyunoss_water']['filepath_prefix'];
    }

    public function run(){
        $listobjects = $this->listobjects($this->ossClient,$this->bucket);
        unset($listobjects[0]);
        foreach($listobjects as $key=>$value){
            if(!empty($this->ossImageProcessUrl)){
                $imgurl = 'http://'.$this->ossImageProcessUrl.'/';
            }else{
                $imgurl = \Yii::getAlias('@web');
            }
            $object['key'] = $value->getKey();
            $object['url'] = $imgurl.$value->getKey();
            $listobjects[$key] = $object;
        }
        return json_encode($listobjects);
    }

    function listObjects($ossClient,$bucket){
        $delimiter = '/';
        $nextMarker = '';
        $maxkeys = 30;
        while(true){
            $options = array(
                'delimiter' => $delimiter,
                'prefix' => $this->filepath_prefix,
                'max-keys' => $maxkeys,
                'marker' => $nextMarker,
            );
            try{
                $listObjectInfo = $ossClient->listObjects($bucket,$options);
            }catch(OssException $e){
                /*\Yii::error(__FUNCTION__.':FAILED\n');
                \Yii::error($e->getMessage()."\n");*/
                return;
            }
            $nextMarker = $listObjectInfo->getNextMarker();
            $listObject = $listObjectInfo->getObjectList();
            $listPrefix = $listObjectInfo->getPrefixList();
            if($nextMarker === ''){
                break;
            }
        }
        return $listObject;
    }
}